# -*- coding: utf-8 -*-
# -*- frozen_string_literal: true -*-

require "optparse"
require "clipboard"
require "lorca/version"
require "lorca/expansions/phrases"

class Lorca
  module CLI # :nodoc:

    # The CLI plugin enables Lorca use through the command line. It autoloads
    # included plugins.
    module LorcaPlugin
      # Run Lorca with +options+ enabled.
      #   lorca = Lorca.add(Lorca::CLI).new
      #   lorca.run
      def run options=$argv
        cli_parse options
      end

      private

      def cli_parse options
        Object.new.extend(CLI).parse options
      end
    end

    def self.load_dependencies expansion, **_
      expansion.add Lorca::Phrases
    end

    def parse argv=$argv, writer:Lorca.new, stash: Clipboard, outlet: $stdout
      cli = OptionParser.new do |parser|
        write_phrase parser, outlet, writer, stash
        display_help parser, outlet
        display_version parser, outlet
      end

      cli.parse!(*argv)

      outlet.puts cli
    end

    private

    def write_phrase cli, outlet, writer, stash
      description = "Generate a passphrase with optional number of WORDS"
      cli.on("-p", "--phrase [WORDS]", Integer, description) { |nw|
        phrase = writer.phrase words: nw
        message = outlet.tty? ? stash_away(phrase, store: stash) : phrase

        outlet.puts message
        exit_cli
      }
    end

    def stash_away phrase, store:
      store.copy phrase
      "passphrase copied to clipboard"
    end

    def display_help cli, outlet
      cli.on_tail("-h", "--help", "Show this message") {
        outlet.puts cli
        exit_cli
      }
    end

    def display_version cli, outlet
      cli.on("--version", "Show Lorca's current version") {
        outlet.puts Lorca::LorcaVersion
        exit_cli
      }
    end

    def exit_cli status: 0
      exit status unless ENV["LORCA_ENV"] == "test"
    end
  end
end
